//
//  BaseTableViewController.m
//  Utils
//
//  Created by enghou on 2018/1/20.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

#import "BaseTableViewController.h"
#import <SVProgressHUD.h>
@interface BaseTableViewController ()
//@property(nonatomic,strong)RefreshedTableView *tableView;

@property(nonatomic,strong)RefreshedTableView *table;

@end

@implementation BaseTableViewController

-(UIView *)view{
    if (!self.table) {
        self.table = [[RefreshedTableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
        self.table.delegate = self;
        self.table.dataSource = self;
    }
    return self.table;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.page = 1;
    [self.tableView performSelector:@selector(setRefreshDelegate:) withObject:self];
}

-(void)beginLoading{
    [SVProgressHUD show];
}

-(void)endLoading{
    [SVProgressHUD dismiss];
    [self.table endAnimation];
}

#pragma mark - BeginRefresh
-(void)beginRefresh{
    [self.tableView performSelector:@selector(endAnimation) withObject:nil];
}

-(void)loadNext{
    [self.tableView performSelector:@selector(endAnimation) withObject:nil];
}

-(void)alertSome:(NSString *)msg{
    UIAlertController *alertController=[UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alertController animated:YES completion:nil];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [alertController dismissViewControllerAnimated:YES completion:nil];
    });
}

-(void)setFull:(BOOL)full{
    _full = full;
    if (_full) {
        UILabel *label = [[UILabel alloc]init];
        label.textColor = [UIColor colorWithHexString:@"999999"];
        label.font = [UIFont systemFontOfSize:14];
        label.frame = CGRectMake(0, 0, self.view.frame.size.width, 30);
        label.text = @"没有更多数据";
        label.textAlignment = NSTextAlignmentCenter;
        self.table.tableFooterView = label;
    }else{
        self.table.tableFooterView = [[UIView alloc]init];
    }
}

-(void)alertSome:(NSString *)msg sureAction:(void(^)(void))act{
    [self alertSome:msg sureAction:act cancelAct:nil];
}

-(void)alertSome:(NSString *)msg sureAction:(void (^)(void))act cancelAct:(void(^)(void))cancel{
    [self alertSome:msg sureTitle:@"确定" sureAction:act cancelTitle:@"取消" cancelAct:cancel];
}

-(void)alertSome:(NSString *)msg sureTitle:(NSString *)sureTitle sureAction:(void(^)(void))sureAct cancelTitle:(NSString *)cancelTitle cancelAct:(void(^)(void))cancel{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:sureTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (sureAct) {
            sureAct();
        }
    }];
    [alert addAction:sureAction];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        if (cancel) {
            cancel();
        }
    }];
    [alert addAction:cancelAction];
    
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)push:(UIViewController *)vc{
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)refreshSuccessWithModel:(BaseModel *)model{
    self.source = [model.list mutableCopy];
    self.page = 1;
    NSDictionary *data = [model.data objectForKey:@"data"];
    if ([[data allKeys]containsObject:@"records"]) {
        NSInteger records = [[data objectForKey:@"records"]integerValue];
        self.totalRecords = records;
    }
    if ([self.source count] == self.totalRecords) {
        self.full = YES;
    }else{
        self.full = NO;
    }
    if ([self.source count] == 0) {
        self.full = NO;
    }
    [self.tableView reloadData];
}

-(void)loadMoreSuccessWithModel:(BaseModel *)model{
    NSDictionary *data = [model.data objectForKey:@"data"];
    if ([[data allKeys]containsObject:@"records"]) {
        NSInteger records = [[data objectForKey:@"records"]integerValue];
        self.totalRecords = records;
    }
    if ([model.list count] == 0) {
        self.full = YES;
        return;
    }else{
        self.page++;
        [self.source addObjectsFromArray:model.list];
        if ([self.source count] == self.totalRecords) {
            self.full = YES;
        }
        [self.tableView reloadData];
    }
}

-(void)chooseOrg{
    ChooseAddressViewController *choose = [[ChooseAddressViewController alloc]init];
    choose.theDelete = self;
    [self push:choose];
}

-(void)commonFailBlockWithModel:(BaseModel *)model{
    if (model.code == 20000) {
        [self alertSome:model.msg sureAction:^{
            LoginViewController *login = [[LoginViewController alloc]init];
            [self.navigationController presentViewController:login animated:YES completion:nil];
        }];
    }else{
        [self alertSome:model.msg];
    }
}
//- (UIView   *)xy_noDataView{
//
//}                //  完全自定义占位图
- (UIImage  *)xy_noDataViewImage{
    return [UIImage imageNamed:@"icon_no_data"];
}           //  使用默认占位图, 提供一张图片,    可不提供, 默认不显示
- (NSString *)xy_noDataViewMessage{
    return @"暂时没有数据";
}         //  使用默认占位图, 提供显示文字,    可不提供, 默认为暂无数据
//- (UIColor  *)xy_noDataViewMessageColor;    //  使用默认占位图, 提供显示文字颜色, 可不提供, 默认为灰色
//- (NSNumber *)xy_noDataViewCenterYOffset;

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.source count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.source count] > indexPath.row) {
        BaseItemModel *model = [self.source objectAtIndex:indexPath.row];
        return model.height;
    }else{
        return 0.0;
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setModel:)]) {
        if ([self.source count] > indexPath.row) {
            BaseItemModel *model = [self.source objectAtIndex:indexPath.row];
            [cell performSelector:@selector(setModel:) withObject:model];
        }
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offY = scrollView.contentOffset.y;
    RefreshedTableView *scroll = (RefreshedTableView *)scrollView;
    if (offY <= 0) {
        [scroll.smileView scrollViewDidScroll];
    }
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    RefreshedTableView *scroll = (RefreshedTableView *)self.tableView;
    [scroll.smileView scrollViewDidEndDraging];
    if (scroll.contentSize.height <= scroll.frame.size.height) {
        if (scroll.contentOffset.y > 20) {
            if (!self.full) {
                if (self.totalRecords != 0) {
                    [scroll.refreshDelegate loadNext];
                }
            }
        }
    }else{
        if (scroll.contentOffset.y > (scroll.contentSize.height - scroll.frame.size.height + 20)) {
            if (!self.full) {
                [scroll.refreshDelegate loadNext];
            }
        }
    }
}

@end
